# This module decodes the output produced by clientencoders/json.js

import simplejson

def decode(args):
  json_args = args.get("json_args")
  if not json_args:
    raise Exception("Incorrectly formatted: 'json_args' missing:%s" % args)
  decoded_args = simplejson.loads(json_args)
  return sterilizeKeywords(decoded_args)
  
def sterilizeKeywords(args):
  """
  Methods can't take Unicode keywords - but that's what JSON produces.
  """
  kwargs = {}
  for key in args:
    kwargs[key.encode('ascii')] = args[key]
  # Now we also have encode the MethodArgs, and GetArgs, if they exist
  cleanup = ['_PTJS_MethodArgs','_PTJS_GetArgs']
  for c in cleanup:
    d = kwargs.get(c)
    if type(d) == dict:
      tmp = {}
      for key in d:
        tmp[key.encode('ascii')] = d[key]
      kwargs[c] = tmp
  return kwargs